package com.sky.dto;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "分页结果")
public class PageDTO<T> {
    @ApiModelProperty("总条数")
    private Long total;
    @ApiModelProperty("总也输")
    private Long pages;
    @ApiModelProperty("集合")
    private List<T> records;

    public static <PO> PageDTO<PO> of(Page<PO> p){
        PageDTO<PO> pageDTO = new PageDTO<>();
        pageDTO.setPages(p.getPages());
        pageDTO.setTotal(p.getTotal());
        List<PO> records = p.getRecords();

        if (records.isEmpty()){
            pageDTO.setRecords(Collections.emptyList());
        }
        pageDTO.setRecords(p.getRecords());

        return pageDTO;
    }

    public static <PO,VO> PageDTO<VO> of(Page<PO> p, Function<PO,VO> convertor){
        PageDTO<VO> pageDTO = new PageDTO<>();
        pageDTO.setPages(p.getPages());
        pageDTO.setTotal(p.getTotal());

        List<PO> records = p.getRecords();
        if (records.isEmpty()){
            pageDTO.setRecords(Collections.emptyList());
        }

        pageDTO.setRecords(records.stream().map(convertor).collect(Collectors.toList()));

        return pageDTO;
    }



}
